//
//  LBCycleScrollView.m
//  PagedScrollView
//
//  Created by  on 14-1-23.
//  Copyright (c) 2014年 Apple Inc. All rights reserved.
//

#import "LBCycleScrollView.h"
#import "NSTimer+LBCycleScrollView.h"

@interface LBCycleScrollView () <UIScrollViewDelegate>

@property (nonatomic , assign) NSInteger totalPageCount;
@property (nonatomic , strong) NSMutableArray *contentViews;
@property (nonatomic , strong) UIScrollView *scrollView;

@property (nonatomic , assign) NSTimeInterval animationDuration;

@end

@implementation LBCycleScrollView

- (void)setTotalPagesCount:(NSInteger)totalPagesCount
{
    _totalPageCount = totalPagesCount;
    if (_totalPageCount > 0) {
        [self configContentViews];
        [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
    }
}

- (id)initWithFrame:(CGRect)frame animationDuration:(NSTimeInterval)animationDuration
{
    self = [self initWithFrame:frame];
    if (animationDuration > 0.0) {
        self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:(self.animationDuration = animationDuration)
                                                               target:self
                                                             selector:@selector(animationTimerDidFired:)
                                                             userInfo:nil
                                                              repeats:YES];
        [self.animationTimer pauseTimer];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.autoresizesSubviews = YES;
        self.scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        self.scrollView.autoresizingMask = 0xFF;
        self.scrollView.contentMode = UIViewContentModeCenter;
        self.scrollView.contentSize = CGSizeMake(3 * CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
        self.scrollView.delegate = self;
        self.scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.scrollView.frame), 0);
        self.scrollView.scrollsToTop = NO;
        self.scrollView.pagingEnabled = YES;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:self.scrollView];
        
        _totalPageCount = 1;
    }
    return self;
}

- (void)setCurrentPageIndex:(NSInteger)currentPageIndex {
    _currentPageIndex = currentPageIndex;
    [self configContentViews];
    [self callViewDidShow];
}

- (void)callViewDidShow {
    if ([_delegate respondsToSelector:@selector(viewAtIndex:index:)]) {
        [_delegate viewDidShow:self index:self.currentPageIndex];
    }
}

#pragma mark -
#pragma mark - 私有函数

- (void)configContentViews {
    for (UIView * view in self.scrollView.subviews) {
        if ([self.contentViews containsObject:view]) {
            view.hidden = YES;
            continue;
        }
        
        [view removeFromSuperview];
    }
    
    UIView *currentView = [self setScrollViewContentDataSource];
    _currentView = currentView;
    
    NSInteger counter = 0;
    for (UIView *contentView in self.contentViews) {
        contentView.userInteractionEnabled = YES;
        contentView.hidden = NO;
        CGRect rightRect = contentView.frame;
        rightRect.origin = CGPointMake(CGRectGetWidth(self.scrollView.frame) * (counter ++), 0);
        
        contentView.frame = rightRect;
        [self.scrollView addSubview:contentView];
    }
    [_scrollView setContentOffset:CGPointMake(_scrollView.frame.size.width, 0)];
    if (_totalPageCount == 1) {
        currentView.frame = CGRectMake(_scrollView.frame.size.width, 0, CGRectGetWidth(currentView.frame), CGRectGetHeight(currentView.frame));
        
        _scrollView.scrollEnabled = NO;
    } else {
        _scrollView.scrollEnabled = YES;
    }
    
}

/**
 *  设置scrollView的content数据源，即contentViews
 */
- (UIView *)setScrollViewContentDataSource {
    NSInteger previousPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex - 1];
    NSInteger rearPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex + 1];
    if (self.contentViews == nil) {
        self.contentViews = [@[] mutableCopy];
    }
    [self.contentViews removeAllObjects];
    UIView *currentView;
    if ([_delegate respondsToSelector:@selector(viewAtIndex:index:)]) {
        [self.contentViews addObject:[_delegate viewAtIndex:self index:previousPageIndex]];
        
        currentView = [_delegate viewAtIndex:self index:_currentPageIndex];
        [self.contentViews addObject:currentView];
        [self.contentViews addObject:[_delegate viewAtIndex:self index:rearPageIndex]];
    }
    
    return currentView;
}

- (NSInteger)getValidNextPageIndexWithPageIndex:(NSInteger)currentPageIndex {
    if(currentPageIndex == -1) {
        return self.totalPageCount - 1;
    } else if (currentPageIndex == self.totalPageCount) {
        return 0;
    } else {
        return currentPageIndex;
    }
}

#pragma mark -
#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.animationTimer pauseTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self.animationTimer resumeTimerAfterTimeInterval:self.animationDuration];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    int contentOffsetX = scrollView.contentOffset.x;
    if(contentOffsetX >= (2 * CGRectGetWidth(scrollView.frame))) {
        self.currentPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex + 1];
    }
    if(contentOffsetX <= 0) {
        self.currentPageIndex = [self getValidNextPageIndexWithPageIndex:self.currentPageIndex - 1];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [scrollView setContentOffset:CGPointMake(CGRectGetWidth(scrollView.frame), 0) animated:YES];
}

#pragma mark -
#pragma mark - 响应事件
- (void)animationTimerDidFired:(NSTimer *)timer {
    // 防止滑动到一部分
    NSInteger index = (self.scrollView.contentOffset.x + CGRectGetWidth(self.scrollView.frame)) / CGRectGetWidth(self.scrollView.frame);
    CGFloat offsetX =  index * CGRectGetWidth(self.scrollView.frame);
    CGPoint newOffset = CGPointMake(offsetX, self.scrollView.contentOffset.y);
    [self.scrollView setContentOffset:newOffset animated:YES];
}

@end
